<template>
  <div class="add_goods_mobile_wrap">
    <div class="nav_box">
      <van-nav-bar
        :title="`${goodsStore.mobileEditGoodsInfo.id ? '编辑' : '添加'}货品`"
        left-text="返回"
        left-arrow
        @click-left="returnClick"
      />
    </div>
    <div class="form_box">
      <van-form @failed="onFailed" @submit="onSubmit">
        <van-cell-group inset>
          <!-- 通过 validator 进行函数校验 -->
          <!-- 货品名称 -->
          <van-field
            v-model="goodsStore.mobileEditGoodsInfo.name"
            name="pattern"
            label="货品名称"
            placeholder="请输入货品名称"
            required
            label-align="right"
            :rules="[{ validator: formReValidator, message: '必须填写货品名称' }]"
          />

          <!-- 类别 -->
          <van-field
            v-model="goodsStore.mobileEditGoodsInfo.categoryName"
            name="validator"
            label="类别"
            placeholder="请选择类别"
            required
            is-link
            readonly
            @click="isShowCategoryPicker = true"
            label-align="right"
            :rules="[{ validator: formReValidator, message: '必须选择类别' }]"
          />
          <!-- 类别选择器 -->
          <van-popup v-model:show="isShowCategoryPicker" position="bottom">
            <van-picker :columns="categoryColumns" @confirm="categoryPickerConfirm" @cancel="isShowCategoryPicker = false" />
          </van-popup>

          <!-- 实验室地址 -->
          <van-field
            v-model="goodsStore.mobileEditGoodsInfo.labAddress"
            name="validator"
            label="实验室地址"
            placeholder="请选择实验室地址"
            required
            label-align="right"
            is-link
            readonly
            @click="isShowLabAddressPicker = true"
            :rules="[{ validator: formReValidator, message: '必须选择实验室地址' }]"
          />
          <!-- 实验室地址选择器 -->
          <van-popup v-model:show="isShowLabAddressPicker" position="bottom">
            <van-picker
              :columns="labAddressColumns"
              @confirm="labAddressPickerConfirm"
              @cancel="isShowLabAddressPicker = false"
            />
          </van-popup>

          <!-- 药品柜 -->
          <van-field
            v-model="goodsStore.mobileEditGoodsInfo.code"
            name="validator"
            label="药品柜"
            placeholder="请输入药品柜"
            required
            label-align="right"
            :rules="[{ validator: formReValidator, message: '必须填写药品柜' }]"
          />

          <!-- 规格描述 -->
          <van-field
            v-model="goodsStore.mobileEditGoodsInfo.specificDesc"
            name="validator"
            label="规格描述"
            placeholder="请输入规格描述"
            label-align="right"
          />

          <!-- 存量 -->
          <van-field
            v-model="goodsStore.mobileEditGoodsInfo.quantity"
            name="validator"
            label="存量"
            placeholder="请输入存量"
            required
            :rules="[{ validator: formReValidator, message: '必须填写存量' }]"
            label-align="right"
          />

          <!-- 单位 -->
          <van-field
            v-model="goodsStore.mobileEditGoodsInfo.measure"
            name="validator"
            label="单位"
            placeholder="请选择单位"
            label-align="right"
            is-link
            readonly
            @click="isShowUnitPicker = true"
          />
          <!-- 单位选择器 -->
          <van-popup v-model:show="isShowUnitPicker" position="bottom">
            <van-picker :columns="unitColumns" @confirm="unitPickerConfirm" @cancel="isShowUnitPicker = false" />
          </van-popup>

          <!-- CAS -->
          <van-field
            v-model="goodsStore.mobileEditGoodsInfo.cas"
            name="validator"
            label="CAS"
            placeholder="请输入CAS"
            label-align="right"
          />

          <!-- 危险标识 -->
          <van-field
            v-model="goodsStore.mobileEditGoodsInfo.dangerRemark"
            name="validator"
            label="危险标识"
            placeholder="请输入危险标识"
            label-align="right"
          />

          <!-- 制造商 -->
          <van-field
            v-model="goodsStore.mobileEditGoodsInfo.manufacturer"
            name="validator"
            label="制造商"
            placeholder="请输入制造商"
            label-align="right"
          />

          <!-- 价格 -->
          <van-field
            v-model="goodsStore.mobileEditGoodsInfo.price"
            name="validator"
            label="价格"
            placeholder="请输入价格"
            label-align="right"
          />

          <!-- 科目 -->
          <van-field
            v-model="goodsStore.mobileEditGoodsInfo.subjectName"
            name="validator"
            label="科目"
            placeholder="请输入科目"
            label-align="right"
          />

          <!-- 项目 -->
          <van-field
            v-model="goodsStore.mobileEditGoodsInfo.projectName"
            name="validator"
            label="项目"
            placeholder="请输入项目"
            label-align="right"
          />
        </van-cell-group>
        <div style="padding: 0 20px; margin-top: 36px">
          <van-button round block type="primary" native-type="submit"> 提交 </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref } from "vue";
import { showToast } from "vant";
export default defineComponent({
  name: "AddGoodsMobile"
});
</script>
<script lang="ts" setup>
// import { closeToast, showLoadingToast } from "vant";
import { useRouter } from "vue-router";
import { useGoodsStore } from "@/stores/modules/goods";
import { addTbGoodsApi, editTbGoodsApi, selectCategoryListApi, selectLaboratoryListApi } from "@/api/modules/goods/index";
import { selectMeasureListApi } from "@/api/modules/measure/index";

const router = useRouter();

const goodsStore = useGoodsStore();

// 显示类别选择器的标识
const isShowCategoryPicker = ref(false);

// 显示实验室地址选择器标识
const isShowLabAddressPicker = ref(false);

// 显示单位选择器
const isShowUnitPicker = ref(false);

// 类别选择器数据
const categoryColumns = ref([]);

// 实验室地址选择器数据
const labAddressColumns = ref([]);

// 单位选择器数据
const unitColumns = ref([]);

// 类别选择器确定事件
const categoryPickerConfirm = ({ selectedOptions }) => {
  goodsStore.mobileEditGoodsInfo.categoryName = selectedOptions[0]?.value;
  isShowCategoryPicker.value = false;
  console.log(goodsStore.mobileEditGoodsInfo.categoryName);
};

// 实验室地址选择器确定事件
const labAddressPickerConfirm = ({ selectedOptions }) => {
  goodsStore.mobileEditGoodsInfo.labAddress = selectedOptions[0]?.text;
  goodsStore.mobileEditGoodsInfo.labId = selectedOptions[0]?.value;
  isShowLabAddressPicker.value = false;
  console.log(goodsStore.mobileEditGoodsInfo.labAddress);
};

// 单位选择器确定事件
const unitPickerConfirm = ({ selectedOptions }) => {
  goodsStore.mobileEditGoodsInfo.measure = selectedOptions[0]?.text;
  isShowUnitPicker.value = false;
  console.log(goodsStore.mobileEditGoodsInfo.measure);
};

// 添加和编辑货品提交点击事件
const onSubmit = async () => {
  // console.log(11);
  // 判断是添加还是编辑
  if (goodsStore.mobileEditGoodsInfo.id) {
    editSubmitFunc();
  } else {
    addSubmitFunc();
  }
};

// 添加提交函数
const addSubmitFunc = async () => {
  // await
  await addTbGoodsApi(goodsStore.mobileEditGoodsInfo)
    .then(res => {
      if (res.result == "success") {
        showToast("添加成功");
        router.back();
      } else if (res.result == "error") {
        showToast(res.msg);
      }
    })
    .catch(err => {
      showToast("添加失败");
    });
  console.log("添加数据", goodsStore.mobileEditGoodsInfo);
};

// 编辑提交函数
const editSubmitFunc = async () => {
  console.log("添加数据", goodsStore.mobileEditGoodsInfo);
  await editTbGoodsApi(goodsStore.mobileEditGoodsInfo)
    .then(res => {
      if (res.result == "success") {
        showToast("修改成功");
        router.back();
      } else if (res.result == "error") {
        showToast(res.msg);
      }
    })
    .catch(err => {
      showToast("修改失败");
    });
};

// 表单必填验证
const formReValidator = val =>
  new Promise(resolve => {
    // if (val == "" || val == null || val == undefined) {
    //   resolve(true);
    // } else {
    //   reject(false);
    // }
    resolve(val !== "" && val != null && val != undefined);
  }).catch(err => {
    console.log("验证错误", err);
    console.log(goodsStore.mobileEditGoodsInfo);
  });

const onFailed = errorInfo => {
  console.log("failed", errorInfo);
  showToast("请将货品信息填写完整");
};

// 返回点击事件
const returnClick = () => {
  console.log("返回货品管理页面");
  router.back();
};

// 查询类别列表的函数
const selectCategoryListFunc = async () => {
  await selectCategoryListApi().then(res => {
    console.table(res.data);
    categoryColumns.value = res.data.map(item => {
      return {
        text: item.name,
        value: item.name
      };
    });
  });
};

// 查询实验室列表的函数
const selectLaboratoryListFunc = async () => {
  await selectLaboratoryListApi().then(res => {
    labAddressColumns.value = res.data.map(item => {
      return {
        text: item.address,
        value: item.id
      };
    });
  });
};

// 查询度量列表的函数
const selectMeasureListFunc = async () => {
  await selectMeasureListApi().then(res => {
    unitColumns.value = res.data.map(item => {
      return {
        text: item.name,
        value: item.name
      };
    });
  });
};

onMounted(() => {
  selectCategoryListFunc();
  selectLaboratoryListFunc();
  selectMeasureListFunc();
});
</script>

<style lang="scss" scoped>
.add_goods_mobile_wrap {
  display: flex;
  flex-direction: column;
  width: 100vw;

  // min-height: calc(100vh - 10px);
  background-color: #f7f8fa;
  .nav_box {
    height: 46px;
  }
  .form_box {
    box-sizing: border-box;

    // flex: 1;
    height: calc(100vh - 10px - 46px);
    padding: 20px 0 40px;
    overflow: scroll;
    letter-spacing: 1px;
  }
}
:deep(.van-field) {
  .van-field__value {
    .van-field__body {
      .van-field__control {
        letter-spacing: 1px;
      }
    }
  }
}
:deep(.van-button) {
  letter-spacing: 6px;
  background: linear-gradient(160.78deg, rgb(29 178 255 / 100%) 0%, rgb(4 123 255 / 100%) 100%);
  border: none;
  border-radius: 55px;
  .van-button__content {
    position: relative;
    left: 2px;
  }
}
</style>
